import { RawData } from "ws";
import { Connection } from "./Connection";
import { InnerMsg } from "../ClientServer";

/**
 * 连接
 */
export class BridgeConnection extends Connection {
    /**
     * 继承重写_onmsg
     * @param data 
     * @param isBinary 
     */
    protected _onmsg(data: RawData, isBinary: boolean) {
        if (isBinary) {
            data = data as ArrayBuffer;
            this._msgParse!.parse(data, (cmd: number, unit8Array: Uint8Array) => {
                const msg: InnerMsg = JSON.parse(Buffer.from(unit8Array).toString('utf-8'))
                if (this.onMsg) {
                    this.onMsg(this, cmd, msg)
                }
            })
        }
        else {
            console.log(`收到文本消息:${data}`)
        }
    }

    /**
     * 消息发送
     * @param cmd 
     * @param data 
     */
    public sendData(cmd: number, data: InnerMsg) {
        const unit8Array: Uint8Array = Buffer.from(JSON.stringify(data), 'utf-8')
        this.send(cmd, unit8Array)
    }
}